#include "mainwidget.h"
#include "ui_mainwidget.h"
#include<QProcess>

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    //初始化ui界面
    initWidgetFunc();

    //连接MySQL数据库
    connectMySQLDBFunc();

    //初始化tableWidget
    initTableWidgetFunc();

    //初始化comBox
    initComboBoxFunc();







}

MainWidget::~MainWidget()
{
    delete ui;
}

//连接mysql数据库函数
void MainWidget::connectMySQLDBFunc()
{

    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setDatabaseName("stock_msdb");//ODBC配置的数据源名称
    db.setUserName("root");
    db.setPassword("root");


    if(db.open())
    {
        qDebug() << "打开数据库成功";
        QSqlQuery query(db);
        QString sql = "select * from commodity_data";
        if(query.exec(sql))
        {

            qDebug() << "查询成功";
        }
        else
        {
            qDebug() << "查询失败";

        }
    }
    else
    {
        QMessageBox::critical(this,"警告","MySQL数据库连接失败...");
    }

}

//初始化界面函数
void MainWidget::initWidgetFunc()
{
    //禁止最大化
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    //固定窗口大小
    setFixedSize(width(),height());


    //设置tableWidget只能读不能写
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    //设置主窗口颜色
    QPalette palette;
    palette.setColor(QPalette::Window,QColor(180,220,130));
    setPalette(palette);


    ui->comboBox_classification->setStyleSheet("color: white;background-color:#8B4726");
    ui->comboBox->setStyleSheet("background-color:#90EE90");

    ui->pushButton_addCom->setStyleSheet("QPushButton{"
                                         "background-color:#43CD80;"  /* 背景颜色 - 亮绿色 */
                                         "color:white;        "      /* 文本颜色 - 白色 */
                                         "border-radius:5px; "       /* 圆角半径 - 5像素 */
                                         "padding:8px;     "        /* 内边距 - 10像素 */
                                         "}"
                                         "QPushButton:hover{"
                                         "background-color:#2E8B57;"
                                         "}");
    ui->pushButton_delCom->setStyleSheet("QPushButton{"
                                         "background-color:#43CD80;"  /* 背景颜色 - 亮绿色 */
                                         "color:white;        "      /* 文本颜色 - 白色 */
                                         "border-radius:5px; "       /* 圆角半径 - 5像素 */
                                         "padding:8px;     "        /* 内边距 - 10像素 */
                                         "}"
                                         "QPushButton:hover{"
                                         "background-color:#2E8B57;"
                                         "}");
    ui->pushButton_storeCom->setStyleSheet("QPushButton{"
                                           "background-color:#43CD80;"  /* 背景颜色 - 亮绿色 */
                                           "color:white;        "      /* 文本颜色 - 白色 */
                                           "border-radius:5px; "       /* 圆角半径 - 5像素 */
                                           "padding:8px;     "        /* 内边距 - 10像素 */
                                           "}"
                                           "QPushButton:hover{"
                                           "background-color:#2E8B57;"
                                           "}");
    ui->pushButton_dataQuery->setStyleSheet("QPushButton{"
                                            "background-color:#43CD80;"  /* 背景颜色 - 亮绿色 */
                                            "color:white;        "      /* 文本颜色 - 白色 */
                                            "border-radius:5px; "       /* 圆角半径 - 5像素 */
                                            "padding:8px;     "        /* 内边距 - 10像素 */
                                            "}"
                                            "QPushButton:hover{"
                                            "background-color:#2E8B57;"
                                            "}");
    ui->pushButton_exportData->setStyleSheet("QPushButton{"
                                             "background-color:#43CD80;"  /* 背景颜色 - 亮绿色 */
                                             "color:white;        "      /* 文本颜色 - 白色 */
                                             "border-radius:5px; "       /* 圆角半径 - 5像素 */
                                             "padding:8px;     "        /* 内边距 - 10像素 */
                                             "}"
                                             "QPushButton:hover{"
                                             "background-color:#2E8B57;"
                                             "}");
    ui->pushButton_dataSummary->setStyleSheet("QPushButton{"
                                              "background-color:#43CD80;"  /* 背景颜色 - 亮绿色 */
                                              "color:white;        "      /* 文本颜色 - 白色 */
                                              "border-radius:5px; "       /* 圆角半径 - 5像素 */
                                              "padding:8px;     "        /* 内边距 - 10像素 */
                                              "}"
                                              "QPushButton:hover{"
                                              "background-color:#2E8B57;"
                                              "}");
    ui->pushButton_deliveryCom->setStyleSheet("QPushButton{"
                                              "background-color:#43CD80;"  /* 背景颜色 - 亮绿色 */
                                              "color:white;        "      /* 文本颜色 - 白色 */
                                              "border-radius:5px; "       /* 圆角半径 - 5像素 */
                                              "padding:8px;     "        /* 内边距 - 10像素 */
                                              "}"
                                              "QPushButton:hover{"
                                              "background-color:#2E8B57;"
                                              "}");
    ui->pushButton_allCom->setStyleSheet("QPushButton{"
                                         "background-color:#43CD80;"  /* 背景颜色 - 亮绿色 */
                                         "color:white;        "      /* 文本颜色 - 白色 */
                                         "border-radius:5px; "       /* 圆角半径 - 5像素 */
                                         "padding:8px;     "        /* 内边距 - 10像素 */
                                         "}"
                                         "QPushButton:hover{"
                                         "background-color:#2E8B57;"
                                         "}");


}

void MainWidget::initComboBoxFunc()
{
    QString sql = "select DISTINCT stock_classification from commodity_data";
    QSqlQuery execSql;
    if(!execSql.exec(sql))
    {
        qDebug() << "执行失败,initComboBoxFunc报错";
    }
    else
    {
        ui->comboBox_classification->clear();
        ui->comboBox_classification->addItem("全部商品");
        while(execSql.next())
        {

            int index = 0;
            for(int i=0;i<ui->comboBox_classification->count();i++)
            {
                //只要comboBox中已经包含了该字段,index = 1,就添加项
                if(ui->comboBox_classification->itemText(i) == execSql.value(0).toString())
                {
                    index = 1;
                }
            }
            if(index == 0)
            {

                ui->comboBox_classification->addItem(execSql.value(0).toString());
            }

        }
    }

}




//初始化table Widget
void MainWidget::initTableWidgetFunc()
{
    //设置表格控件 字体的大小
    ui->tableWidget->setFont(QFont("宋体",9));

    //设置列数和行数
    ui->tableWidget->setColumnCount(10);
    ui->tableWidget->setRowCount(200);

    //初始化表格控件列宽度
    //ui->tableWidget->setColumnWidth(0,80);

    //设置水平表头
    QStringList strList;
    strList << "商品编号" << "商品名称" << "商品数量" << "商品单价" << "供应商家" << "负责人" << "入库时间" << "出库时间"
            << "备注"  << "商品分类";
    ui->tableWidget->setHorizontalHeaderLabels(strList);

    //初始化数据
    QString sql = QString("select * from commodity_data");

    //调用遍历结果集函数
    traverseQueryResFunc(sql);


}

//遍历查询结果
void MainWidget::traverseQueryResFunc(QString sql)
{
    qDebug() << "traverseQueryResFunc()被执行...";

    QSqlQuery query;
    // 保留表头，清空单元格内所有内容
    ui->tableWidget->clearContents();

    query.exec(sql);
    int i = 0;
    while(query.next())
    {
        QString stockId = query.value(0).toString();
        QString stockName = query.value(1).toString();
        QString stockAmount = query.value(2).toString();
        QString stockUnitPrice = query.value(3).toString();
        QString supplier = query.value(4).toString();
        QString director = query.value(5).toString();
        QString storeTime = query.value(6).toString();
        QString deliveryTime = query.value(7).toString();
        QString remarks = query.value(8).toString();
        QString stockClassification = query.value(9).toString();

        //将对应的字符串设置到widgetList中
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(stockId));
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(stockName));
        ui->tableWidget->setItem(i,2,new QTableWidgetItem(stockAmount));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(stockUnitPrice));
        ui->tableWidget->setItem(i,4,new QTableWidgetItem(supplier));
        ui->tableWidget->setItem(i,5,new QTableWidgetItem(director));
        ui->tableWidget->setItem(i,6,new QTableWidgetItem(storeTime));
        ui->tableWidget->setItem(i,7,new QTableWidgetItem(deliveryTime));
        ui->tableWidget->setItem(i,8,new QTableWidgetItem(remarks));
        ui->tableWidget->setItem(i,9,new QTableWidgetItem(stockClassification));
        i++;
    }
}

void MainWidget::on_pushButton_storeCom_clicked()
{
    InputWidget *inputWidget = new InputWidget();
    inputWidget->setAttribute(Qt::WA_DeleteOnClose);
    QEventLoop loop;
    connect(inputWidget,&InputWidget::windowClosed,&loop,&QEventLoop::quit);

    //将 inputWidget 设置为应用程序模态窗口
    //当 inputWidget 显示时，整个应用程序的其他窗口都会被阻塞，无法进行交互操作。
    inputWidget->setWindowModality(Qt::ApplicationModal);
    inputWidget->show();
    loop.exec();
    traverseQueryResFunc("select * from commodity_data");
}

//点击新增商品按钮
void MainWidget::on_pushButton_addCom_clicked()
{
    AddCommodityWidget *addCommodityWidget = new AddCommodityWidget();



    addCommodityWidget->setAttribute(Qt::WA_DeleteOnClose);  // 关键设置
    // 创建局部事件循环
    QEventLoop loop;
    connect(addCommodityWidget, &AddCommodityWidget::windowClosed, &loop, &QEventLoop::quit);

    //模态显示
    addCommodityWidget->setWindowModality(Qt::ApplicationModal);
    addCommodityWidget->show();  // 显示窗口
    loop.exec();                 // 阻塞在此处，直到窗口关闭



    qDebug() << addCommodityWidget->stockClassifiaction;
    //只要addCommodityWidget->stockClassifiaction正确，就把它添加分类到ComboBox
    if(!(addCommodityWidget->stockClassifiaction.isEmpty() ||  addCommodityWidget->stockClassifiaction == ""))
    {
        int index = 0;
        //如果combox中没有这个分类，添加分类
        for(int i=0;i<ui->comboBox_classification->count();i++)
        {
            if(addCommodityWidget->stockClassifiaction == ui->comboBox_classification->itemText(i))
            {
                index = 1;
            }
        }
        if(index == 0)
        {
            initComboBoxFunc();
        }
    }


    traverseQueryResFunc("select * from commodity_data");

}

//点击商品出库按钮
void MainWidget::on_pushButton_deliveryCom_clicked()
{

    OutputWidget *outputWidget = new OutputWidget();
    outputWidget->setAttribute(Qt::WA_DeleteOnClose);
    QEventLoop loop;
    connect(outputWidget,&OutputWidget::windowClosed,&loop,&QEventLoop::quit);
    outputWidget->setWindowModality(Qt::ApplicationModal);
    outputWidget->show();
    loop.exec();
    traverseQueryResFunc("select * from commodity_data");
}

//点击删除商品按钮
void MainWidget::on_pushButton_delCom_clicked()
{
    //获取当前你选择的行进行删除:商品记录数据
    int row = ui->tableWidget->currentRow();
    //根据 index 来获取对应商品的编号
    QString strValue = ui->tableWidget->model()->index(row,0).data().toString();

    //判断对应商品编号是否为空
    if(strValue.isEmpty())
    {
        QMessageBox::critical(this,"错误","删除的商品编号不能为空,请重新检查...");
        return;
    }

    int iClicked = QMessageBox::warning(this,"警告",QString("请确认是否要删除%1号商品?").arg(strValue),QMessageBox::Yes,QMessageBox::No);
    //判断用户点击的是Yes 还是 No
    if(iClicked == QMessageBox::Yes)
    {
        QSqlQuery sqlDel;
        QString sql = QString("delete from commodity_data where stock_id = %1").arg(strValue);

        if(sqlDel.exec(sql))
        {
            QMessageBox::information(this,"成功","恭喜你,删除商品成功!");


            //对tableWidget内的数据进行刷新操作
            traverseQueryResFunc(QString("select * from commodity_data"));

            //对Combox进行刷新操作
            initComboBoxFunc();

        }
        else
        {
            QMessageBox::critical(this,"失败","删除商品失败,请重新检查...");
        }
    }
    else
    {
        return;
    }
}



//导出数据(该函数功能：导出表格控件数据，直接生成Excel文件保存)
void MainWidget::on_pushButton_exportData_clicked()
{
    QTableWidget *table = ui->tableWidget;
    int colCount = table->columnCount();

    //1.检查有效数据
    bool hasData = false;
    for (int row = 0; row < table->rowCount(); row++) {
        if (table->item(row, 0) && !table->item(row, 0)->text().isEmpty()) {
            hasData = true;
            break;
        }
    }
    if (!hasData) {
        QMessageBox::warning(this, "提示", "没有有效数据可导出！");
        return;
    }

    //2.初始化 Excel 对象
    QAxObject *excel = new QAxObject;
    //判断系统是否安装Office的运行时环境
    if (!excel->setControl("Excel.Application")) {
        QMessageBox::critical(this, "错误", "无法创建 Excel 对象，请确认已安装 Microsoft Excel。");
        delete excel;
        return;
    }
    //excel->setProperty("Visible", true); // 临时显示窗口（调试）

    //3.工作簿与工作表的创建
    QAxObject *workbooks = excel->querySubObject("Workbooks");
    QAxObject *workbook = workbooks->querySubObject("Add");
    QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);

    //4.写入表头
    for (int col = 0; col < colCount; col++) {
        QTableWidgetItem *header = table->horizontalHeaderItem(col);
        QString title = header ? header->text() : "";
        QAxObject *cell = worksheet->querySubObject("Cells(int,int)", 1, col + 1);//定位一个单元格
        cell->dynamicCall("SetValue(const QString&)", title);//往单元格中加入内容
        delete cell;
    }

    //5.写入数据
    int excelRow = 2;
    for (int row = 0; row < table->rowCount(); row++) {
        if (!table->item(row, 0) || table->item(row, 0)->text().isEmpty()) {
            continue;
        }
        for (int col = 0; col < colCount; col++) {
            QTableWidgetItem *item = table->item(row, col);
            QString value = item ? item->text() : "";
            QAxObject *cell = worksheet->querySubObject("Cells(int,int)", excelRow, col + 1);
            cell->dynamicCall("SetValue(const QString&)", value);
            delete cell;
        }
        excelRow++;
    }

    //6.调整列宽
    QAxObject *usedRange = worksheet->querySubObject("UsedRange");
    usedRange->querySubObject("Columns")->dynamicCall("AutoFit()");
    delete usedRange;

    //7.保存文件处理
    QString fileName = "商品库存数据_" + QDateTime::currentDateTime().toString("yyyyMMdd") + ".xlsx";
    QString filePath = QFileDialog::getSaveFileName(
                this,
                "保存文件",
                fileName,
                "Excel文件 (*.xlsx)"
                );
    if (!filePath.isEmpty()) {
        if (!filePath.endsWith(".xlsx", Qt::CaseInsensitive)) {
            filePath += ".xlsx";
        }
        //将文件路径中的目录分隔符转换为当前操作系统的标准格式
        QString nativePath = QDir::toNativeSeparators(filePath);
        workbook->dynamicCall("SaveAs(const QString&)", nativePath);
        QMessageBox::information(this, "成功", QString("文件已保存至：\n%1").arg(nativePath));
    }

    //8.释放资源与进程清理
    workbook->dynamicCall("Close()");
    excel->dynamicCall("Quit()");
    delete worksheet;
    delete workbook;
    delete workbooks;
    delete excel;

    //9.强制终止 Excel 进程
    QProcess::execute("taskkill /F /IM EXCEL.EXE");
}







//点击数据汇总按钮
void MainWidget::on_pushButton_dataSummary_clicked()
{
    DataSumWidget *dataSumWidget = new DataSumWidget();
    dataSumWidget->setWindowModality(Qt::ApplicationModal);
    dataSumWidget->show();
}

//点击查询按钮
void MainWidget::on_pushButton_dataQuery_clicked()
{

    QSqlQuery query;
    QString sql;
    if(ui->comboBox->currentText() == "根据商品编号查询")
    {
        QString strId = "stock_id=" + ui->lineEdit->text();
        sql = QString("select * from commodity_data where %1").arg(strId);
    }
    else if(ui->comboBox->currentText() == "根据商品名称查询")
    {
        QString strName =ui->lineEdit->text();
        sql = QString("select * from commodity_data where stock_name = '%1'").arg(strName);
    }
    else if(ui->comboBox->currentText() == "根据负责人姓名查询")
    {
        QString strDirector =ui->lineEdit->text();
        sql = QString("select * from commodity_data where director = '%1'").arg(strDirector);
    }


    query.exec(sql);

    traverseQueryResFunc(sql);
}

//商品总览
void MainWidget::on_pushButton_allCom_clicked()
{
    traverseQueryResFunc("select * from commodity_data");
}



//商品分类combox
void MainWidget::on_comboBox_classification_activated(const QString &arg1)
{
    if(arg1 == " ")
    {
        return;
    }
    QString sql;
    if(arg1 == "全部商品")
    {
        sql = "select * from commodity_data";
    }
    else
    {
        sql = QString("select * from commodity_data where stock_classification = '%1'").arg(arg1);
    }

    traverseQueryResFunc(sql);


}
